package logic

import (
	"context"
	"fmt"
	"hema-fresh/model/mysql"

	"hema-fresh/hemarpc/hemarpc"
	"hema-fresh/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductAddLogic {
	return &ProductAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductAddLogic) ProductAdd(in *hemarpc.ProductAddRequest) (*hemarpc.ProductAddResponse, error) {
	// todo: add your logic here and delete this line

	var findProduct mysql.Product
	mysql.DB.Debug().Where("name = ?", in.Name).Find(&findProduct)

	if findProduct.ID != 0 {
		return nil, fmt.Errorf("当前图书已存在,禁止添加")
	}

	product := mysql.Product{
		Name:    in.Name,
		Price:   float64(in.Price),
		ClassId: int(in.ClassId),
	}
	err := mysql.DB.Debug().Create(&product).Error

	if err != nil {
		return nil, err
	}

	return &hemarpc.ProductAddResponse{
		ProductId: int64(product.ID),
	}, nil
}
